package cn.yuanqiao.activiti.listener;

import cn.yuanqiao.activiti.service.IActArchiveDataService;
import cn.yuanqiao.common.exception.activiti.ArchiveProcessException;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: WritsArchiveBorrowListener
 * @Description: 类的描述
 * @author: lihuahua
 * @date: 2023/6/5 19:24
 * @Blog: huahuacoco.top
 */

@Component("ArchiveSaveComplatetListener")
public class ArchiveSaveComplatetListener implements ExecutionListener {

    @Autowired
    private IActArchiveDataService actArchiveDataService;

    @Override
    public void notify(DelegateExecution execution) {
        String processInstanceId = execution.getProcessInstanceId();
        Object obj = execution.getVariable("archiveData");

        if (obj == null){
            throw new ArchiveProcessException("档案数据不能为空");
        }
        List<Map<String,Object>> archiveData = (List<Map<String, Object>>) obj;
        Iterator<Map<String, Object>> iterator = archiveData.iterator();
        List<Map<String,Object>> archiveDataNotAgree = new ArrayList<>();
        while (iterator.hasNext()){
            Map<String, Object> archiveVariable = iterator.next();
            Object archiveAgreeStatus = archiveVariable.get("archiveAgreeStatus");
            if (archiveAgreeStatus!=null){
                String status = String.valueOf(archiveAgreeStatus);
                if ("0".equals(status)){
                    archiveDataNotAgree.add(archiveVariable);
                    iterator.remove();
                }
            }
        }
        if (archiveData.size()!=0){
            actArchiveDataService.batchUpdateArchiveState(archiveData,"5");
            //添加归档章
            actArchiveDataService.addSeal(archiveData);
        }
        if (archiveDataNotAgree.size()!=0){
            actArchiveDataService.batchUpdateArchiveState(archiveDataNotAgree,"2");
        }
        System.out.println("同意归档，修改数据");

    }
}
